<?php
include('../../include/functions.inc.php');
include('../../include/objects/business/Bo_Facturacion.php');
include('../../include/objects/system/Sys_ConfigManager.php');
Bo_Facturacion::$db = $db;
Bo_Facturacion::$user = $user;

/**
 * 
 * @param type $dbs
 */
function getAlumnosEmpresa($db) {
    $idEmpresa = getParam("idEmpresa");
    ?>
    <table width="100%" class="table table-bordered table-striped table-hover" >
        <tbody>   
            <tr>
                <th>
                    Carnet
                </th>
                <th >
                    Estudiante
                </th>
                <th>
                    Observaciones de pago
                </th>
                <th>
                    &nbsp;
                </th>
            </tr>

            <?php
            if (!isEmpty($idEmpresa)) {
                $estudiantes = $db->queryToArray(sprintf("select *
            from cllg_student where FK_EMPRESA=%s", $idEmpresa));
                foreach ($estudiantes as $e) {
                    $account = $db->query_select("cllg_account",sprintf("FK_STUDENT='%s'", $e['ID']));
                    $obsPago = $db->query_select("cllg_table_valuebyfield",sprintf("PK_RECORD=%s AND FK_TABLEFIELD='OBSERVACIONES_PAGO'", $e['ID']));
                    $studName = $e['SECOND_NAME'] != NULL ? $e['FIRST_NAME']." ".$e['SECOND_NAME']." ".$e['LAST_NAME'] : $e['FIRST_NAME']." ".$e['LAST_NAME'];
                    ?>
                    <tr>
                        <td>
                            <?php echo $e["ID"]; ?>
                        </td>
                        <td style="<?php echo (count($account) == 0 ? "text-decoration:line-through" : ""); ?>">
                            <?php echo $studName; ?>
                        </td>
                        <td >
                            <?php echo (count($obsPago) > 0 ? $obsPago[0]['VALUE'] : ""); ?>
                        </td>
                        <?php
                        if (count($account) > 0){
                        ?>
                        <td>
                            <a class="btn btn-primary" href="javascript:loadDataAlumno('<?php echo $e["ID"]; ?>','<?php echo $studName; ?>');">Cargar</a>
                        </td>
                        <?php
                        }else{
                        ?>
                        <td>
                            <a class="btn btn-primary" href="javascript:alert('El alumno no tiene una cuenta en esta entidad!')">Cargar</a>
                        </td>
                        <?php
                        }
                        ?>
                    </tr>
                    <?php
                }
            } else {
                ?>
                <tr><td colspan="4">-Vacio-</td> </tr>  <?php
            }
            ?>
        </tbody>
    </table>
    <?php
}

/**
 * 
 * @param type $db
 * @param type $id
 * @return type
 */
function findStudentCta($db, $id) {
    $datos = array();
    $l = $db->query_select('cllg_account', "FK_STUDENT=$id");
    $ac = $l[0];
    if (count($ac) > 0) {
        return $ac;
    } else {
        $datos = array('ERROR' => 'NO TIENE CUENTA CORRIENTE EN ESTA ENTIDAD!');
    }
}

/**
 * 
 * @param type $db
 */
function getCargosAlumnoEmpresa($db) {
    $cta = findStudentCta($db, getParam("idAlumno"));
    ?>
    <div>
        <table width="100%" class="table table-bordered table-striped table-hover">
            <tbody>
                <?php
                $strQuery = "SELECT  cllg_account.ID FK_ACCOUNT,
                                cllg_cheque.NUMERO 
                        FROM    cllg_cheque,
                                cllg_factura,
                                cllg_account
                        WHERE   cllg_account.ID = " . $cta["ID"] . "
                        AND     cllg_cheque.STATUS = 0
                        AND     cllg_cheque.FECHA_REPOSICION IS NULL
                        AND     cllg_cheque.FK_FACURA = cllg_factura.ID
                        AND     cllg_factura.FK_STUDENT = cllg_account.FK_STUDENT";
                $arrInfo = $db->query_toArray($strQuery);
                if (isset($arrInfo[0])) {
                    ?>
                    <tr>
                        <td colspan="8" style="color: red; font-size: 15px;">El estudiante tiene cheque(s) rechazado(s)!!!</td>
                    </tr>    
                    <?php
                }
                ?>
                <tr>
                    <th width="5%" style="width:5%" >&nbsp;</th>
                    <th width="30%" >Cargo</th>
                    <th width="10%" >Fecha Pago</th>
                    <th width="9%" >Abonos</th>
                    <th width="9%" >Saldo Pendiente</th>
                    <th width="8%" >Mora</th>
                    <th width="15%" >Total a Pagar</th>
                    <th width="25%" >Este Abono</th>
                </tr>
                <?php
                $f = date('y-d-m');
                $r = $db->query_select("cllg_cargo", "(DATE_PAYED IS NULL OR TOTAL_PENDIENTE>0 ) AND FK_ACCOUNT=" . $cta["ID"], "DATE_LIMIT");
                $index = 0;
                $co = 0;
                foreach ($r as $c) {
                    $sig = $c["MONEDA"] == 1 ? "Q" : "$";
                    $now = date("Y-m-d", strtotime(getParam("fechapago")));
                    //echo $now;
                    $penal = 0;
                    $total = $c['AMOUNT'];
                    $originalTotal = $total;
                    $parciales = "No";

                    if (isset($c["TOTAL_PENDIENTE"]) && $c["TOTAL_PENDIENTE"] > 0) {
                        $total = $c['TOTAL_PENDIENTE'];
                        $originalTotal = $total;
                        $parciales = "Si";
                    }
                    if ($c["TOTAL"] > 0) { // SI NO TIENE PAGOS ANTERIORES
                        if ($c["TOTAL"] > $c['AMOUNT']) { //SI NO TIENE DESCUENTOS
                            $montoMora = $c['PENALTY'] + $c['AMOUNT'];
                        } else {
                            $sum = getTotalAbono($db, $c["ID"]);
                            $montoMora = $sum + $c['TOTAL_PENDIENTE'];
                        }
                        if ($montoMora != $c['TOTAL']) { //SI NO TIENE MORA APLICADA
                            if (strtotime($now) > strtotime($c['DATE_LIMIT'])) {
                                $penal = $c['PENALTY'];
                                $total+=$penal;
                            }
                        }
                    } else {
                        if (strtotime($now) > strtotime($c['DATE_LIMIT'])) {
                            $penal = $c['PENALTY'];
                            $total+=$penal;
                        }
                    }
                    
                    if($c["TOTAL_PENDIENTE"] > 0 && strtotime($now) > strtotime($c['DATE_LIMIT'])){
                    $cargo = $c['AMOUNT'] + $c['PENALTY'];
                    if($c['TOTAL'] < $cargo){
                        $penal = $c['PENALTY'] != null ? $c['PENALTY'] : 0;
                        $total += $penal;
                    }
                }

                    $row = array("ID" => $c["ID"], "MONEDA" => $c["MONEDA"],
                        "DESCRIPTION" => $c['DESCRIPTION'],
                        "AMOUNT" => number_format($c['AMOUNT'], 2, ".", ","),
                        "PENAL" => number_format(floatval($penal), 2, ".", ","),
                        "PENAL_REF" => number_format(floatval($penal), 2, ".", ","),
                        "TOT" => $total, "DATE_LIMIT" => $c['DATE_LIMIT'],
                        "TIPO_CARGO" => $c['TIPO_CARGO']);
                    $index = $c["ID"];
                    $json_string = json_encode($row);
                    ?>
                    <tr>
                        <td><input alt="<?php echo $index; ?>" type="checkbox" id="chk_<?php echo $index; ?>" name="chk_<?php echo $index; ?>"  checked=""
                                   onclick='javascript:marcar(<?php echo $json_string; ?>, this);' /></td>
                        <td><?php echo $c['DESCRIPTION']; ?></td>
                        <td><?php echo $c['DATE_LIMIT']; ?></td>
                        <td><?php echo $parciales; ?></td>
                        <td><?php echo $sig . " " . number_format($originalTotal, 2, ".", ","); ?></td>
                        <td><?php echo $sig . " " . number_format(floatval($penal), 2, ".", ","); ?></td>
                        <td><?php echo $sig . " " . number_format($total, 2, ".", ","); ?></td>
                        <td>
                            <input alt="<?php echo $index; ?>" type="text" id="txt_<?php echo $index; ?>" readonly="readonly" name="txt_<?php echo $index; ?>" value="<?php echo number_format($total, 2, ".", ","); ?>" />
                        </td>
                    </tr>
                    <?php
                    $co++;
                }
                ?>
            </tbody>
        </table>
    </div>
    <?php
}

function facturar($pagoEmpresa) {
    $boFac = new Bo_Facturacion();
    $boFac->facturarEmpresa($pagoEmpresa);
}

function imprimir() {
    $boFac = new Bo_Facturacion();
    switch(getParam("print")){
        case "main":{
            $boFac->imprimir2();
            break;
        }
        case "back":{
            $boFac->imprimirBack();
        }
    }
}

$op = getParam("op");
Bo_Facturacion::$db = $db;
Bo_Facturacion::$user = $user;
Sys_ConfigManager::$db = $db;
switch ($op) {
    case "alumnos": {
            getAlumnosEmpresa($db);
            break;
        }
    case "cargos": {
            getCargosAlumnoEmpresa($db);
            break;
        }
    case "facturar": {
            $data = !isEmpty(getParam("data")) ? getParam("data") : "";
            $pagoEmpresa = json_decode($data,TRUE);
            facturar($pagoEmpresa);
            break;
        }
    case "print": {
            include "../../include/tcpdf/config/lang/spa.php";
            include "../../include/tcpdf/tcpdf.php";
            include "../../include/conversor.php";
            imprimir();
        }
    default: {
            break;
        }
}
?>